<template>
  <div class="quickReplyLi" v-loading="loading">
    <!-- 快捷回复表格表头 -->
    <el-row class="box_head">
      <el-col :span="2" v-if="currentSort">
        <span></span>
      </el-col>
      <el-col :span="2">
        <el-checkbox class="check_box" :indeterminate="isIndeterminate" v-model="checkAll" @change="replyCheck('all')"></el-checkbox>
      </el-col>
      <el-col :span="3">
        <span>{{$t('webchat.quickWords2')}}</span>
      </el-col>
      <el-col :span="currentSort ? 12 : 10">
        <span>{{$t('business.replyContent')}}</span>
      </el-col>
      <el-col :span="4" v-if="!currentSort">
        <span>{{$t('webchat.replyCategory')}}</span>
      </el-col>
      <el-col :span="2">
        <span>{{$t('webchat.useConut')}}</span>
      </el-col>
      <el-col :span="3">
        <span>{{$t('public.operate')}}</span>
      </el-col>
    </el-row>
    <!-- 快捷回复拖拽组件 -->
    <draggable class="box_li_parent" v-if="dataObj.list.length" :list="dataObj.list" :options="{handle:'.draggable_handle'}" @start="drag=true" @end="dragEnd">
      <el-row class="box_li" v-for="(item, index) in dataObj.list" :key="index">
        <!-- 快捷回复拖拽按钮 -->
        <el-col :span="2" v-if="currentSort">
          <span class="draggable_handle iconfont icon-shunxutuozhuai"></span>
        </el-col>
        <!-- 快捷回复复选框 -->
        <el-col :span="2">
          <el-checkbox class="check_box" v-model="item.checked" @change="replyCheck"></el-checkbox>
        </el-col>
        <!-- 快捷回复快捷词 -->
        <el-col :span="3">
          <span :title="item.quickContent" v-html="item.quickContentShow ? '#' + item.quickContentShow : ''"></span>
        </el-col>
        <!-- 快捷回复内容 -->
        <el-col class="itemContent" :span="currentSort ? 12 : 10">
          <span :title="item.content" v-html="item.contentShow"></span>
        </el-col>
        <!-- 快捷回复所属分类 -->
        <el-col :span="4" class="itemSortName" v-if="!currentSort">
          <span :title="item.parentSortName">{{item.parentSortName}}</span>
        </el-col>
        <el-col :span="2" class="itemSortName">
          <span :title="item.num">{{item.num}}</span>
        </el-col>
        <!-- 快捷回复修改&&删除按钮 -->
        <el-col :span="3">
          <span class="edit" @click = "editQuickReply(item)">{{$t('public.edit')}}</span>
          <span class="del" @click = "deleteQuickReply(item, false)">{{$t('public.delete')}}</span>
        </el-col>
      </el-row>
    </draggable>
    <div v-else class="no_data">{{$t('public.noData')}}</div>
  </div>
</template>
<script>
  import draggable from 'vuedraggable'
  import bus from '@/store/eventBus'
  import { deepClone } from '@utils/m7Utils'
  import { orderBy } from 'lodash'
  export default {
    name: 'quickReplyLi',
    data () {
      return {
        dataObj: {                  //  快捷回复数据
          list: []
        },
        queryConFlag: false,
        searchCon: '',
        checkedCount: 0,            //  当前批量选中数量
        loading: false,
        checkAll: false,            //  批量选中是否选中所有
        sortDataClone: [],
        isIndeterminate: false      //  批量选中，部分选中
      }
    },
    props: {
//      刷新快捷回复随机数
      randomReply: {
        type: Number,
        default: 0
      },
//      当前选中类别_id
      currentSort: {
        type: String,
        default: ''
      },
//      所有分类数据，全部类别的时候，展示所属分类的操作
      sortData: {
        type: Array,
        default: []
      },
//      操作类型，公共快捷回复还是自定义快捷回复
      dataType: {
        type: String,
        default: ''
      }
    },
    watch: {
//      刷新快捷回复数据
      randomReply () {
        this.searchCon = ''
        this.refresh()
      }
    },
    methods: {
//      刷新
      refresh (page, content) {
        let self = this
        self.loading = true
        let data = {moduleType: 'webchat'}
        let active = ''
//        当前已经选中，加载当前选中分类的数据
        if (self.currentSort) {
          data = {
            tagParentId: self.currentSort,
            content: '',
            moduleType: 'webchat'
          }
//          搜索结果的翻页，会带上content
          if (content) {
            data.content = content
          }
          active = 'newQueryQuickReply'
          if (self.dataType === 'customize') {
            active = 'newQueryAgentQuickReply'
          }
//        当前没有选中分类，加载所有分类的数据
        } else {
          data = {
            tagParentId: '',
            content: content,
            limit: 20,
            page: page,
            moduleType: 'webchat'
          }
          active = 'queryAllQuickReplyNew'
          if (self.dataType === 'customize') {
            active = 'queryAllAgentQuickReplyNew'
          }
        }
        self.$store.dispatch(active, data).then(res => {
          if (res && res.success) {
            if (self.dataType === 'customize') {
              bus.$emit('refreshAgentReply')
            }
            self.dataObj.list = []
            let resData = deepClone(res.data || res.quickreplys || res.list)
//            快捷回复初始化
            let sortDataNew = []
            if (self.sortData.length) {
              sortDataNew = self.sortData
            } else {
              sortDataNew = self.sortDataClone
            }
            self.queryConFlag = false
            if (self.searchCon) {
              self.queryConFlag = true
            }
//            兼容割接之后的老数据
            resData.forEach((item) => {
              self.$set(item, 'checked', false)
              if (typeof item.quickContent === 'undefined') {
                self.$set(item, 'quickContent', '')
              }
//              设置快捷回复的分类名称
              sortDataNew.forEach((obj) => {
                if (item.tagParentId === obj._id) {
                  self.$set(item, 'parentSortName', obj.name)
                }
              })
              this.$set(item, 'contentShow', item.content)
              this.$set(item, 'quickContentShow', item.quickContent)
              this.$set(item, 'num', item.num || 0)
              if (self.queryConFlag && self.searchCon) {
                if (item.content.indexOf(self.searchCon) > -1) {
                  let val = item.content.replace(self.searchCon, '<b style="color: #ff6161">' + self.searchCon + '</b>')
                  this.$set(item, 'contentShow', val)
                }
                if (item.quickContent.indexOf(self.searchCon) > -1) {
                  let val1 = item.quickContent.replace(self.searchCon, '<b style="color: #ff6161">' + self.searchCon + '</b>')
                  this.$set(item, 'quickContentShow', val1)
                }
              }
              self.dataObj.list.push(item)
            })
            let arr = deepClone(self.dataObj.list)
//            对快捷回复进行排序
            self.dataObj.list = deepClone(self.queueSort(arr))
            self.loading = false
            self.checkedCount = 0
            self.checkAll = false
            self.isIndeterminate = false
            let count = res.count || resData.length
            bus.$emit('queryReply', {count: count, dataType: this.dataType})
            bus.$emit('checkBoxClick', {data: self.isIndeterminate, dataType: this.dataType})
          }
        })
      },
//      快捷回复排序，根据sort和更新时间排序
      queueSort (data) {
        let dataNew = deepClone(data)
        if (this.currentSort) {
          dataNew = orderBy(data, [(o) => {
            let aa = o['sort'] || -1
            return aa
          }, (o) => {
            let aa = o['updatedTime'] || 0
            return aa
          }], ['asc', 'desc'])
        }
        return dataNew
      },
//      移动快捷回复
      dragEnd (data) {
        let self = this
        let active = 'newBatchUpdateQuickReply'
        if (self.dataType === 'customize') {
          active = 'newBatchUpdateAgentQuickReply'
        }
        let _id = self.dataObj.list[data.newIndex]._id
        self.$store.dispatch(active, {_id: _id, sort: data.newIndex, tagParentId: self.currentSort}).then(res => {
          if (res && res.success) {
            self.$message.success(self.$t('business.updateSuccess'))
          }
          self.refresh()
        })
      },
//      编辑快捷回复
      editQuickReply (data) {
        this.$emit('editReply', {data: data, dataType: this.dataType})
      },
//      删除||批量删除快捷回复
      deleteQuickReply (val, type) {
        let self = this
        let str = this.$t('webchat.sureDeleteCurrentReply')
        if (type) {
          str = this.$t('webchat.sureBatchDeleteCurrentReply')
        }
        self.$confirm(str, self.$t('public.tip'), {
          confirmButtonText: self.$t('public.confirm'),
          cancelButtonText: self.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          let data = {
            ids: []
          }
//          批量删除需要传输id数组
          if (type) {
            self.dataObj.list.forEach((item) => {
              if (item.checked) {
                data.ids.push(item._id)
              }
            })
          } else {
            data.ids.push(val._id)
          }
          let actionData = 'newDeleteQuickReply'
          if (self.dataType === 'customize') {
            actionData = 'newDeleteAgentQuickReply'
          }
          self.$store.dispatch(actionData, data).then(req => {
            if (req && req.success) {
              self.$message.success(self.$t('monitor.deleteSuccess'))
              self.refresh()
            }
          })
        }).catch(() => {})
      },
//      选中快捷回复
      replyCheck (val) {
//        val不是'all'代表是选中了单个的快捷回复，选中单个的值是true或者false
        if (typeof val !== undefined && typeof val !== 'string') {
          if (val) {
            this.checkedCount += 1
          } else {
            this.checkedCount -= 1
          }
          if (this.checkedCount < 0) {
            this.checkedCount = 0
          }
          this.checkAll = this.checkedCount === this.dataObj.list.length
          this.isIndeterminate = this.checkedCount > 0 && this.checkedCount < this.dataObj.list.length
          let flag = this.isIndeterminate || this.checkAll
          bus.$emit('checkBoxClick', {data: flag, dataType: this.dataType})
        } else {
//        全选按钮点击
          let checkFlag = false
//          如果当前已经全部选中，则进行取消全选操作
          if (this.checkedCount === this.dataObj.list.length) {
            this.checkedCount = 0
            this.checkAll = false
            checkFlag = false
          } else {
//          如果当前没有全部选中，则进行全选操作
            this.checkedCount = this.dataObj.list.length
            this.checkAll = true
            checkFlag = true
          }
          this.dataObj.list.forEach((item) => {
            this.$set(item, 'checked', checkFlag)
          })
          this.isIndeterminate = this.checkedCount > 0 && this.checkedCount < this.dataObj.list.length
          let flag = this.isIndeterminate || this.checkAll
          bus.$emit('checkBoxClick', {data: flag, dataType: this.dataType})
        }
      }
    },
    components: {
      draggable,
      bus
    },
    mounted () {
//      删除快捷回复
      bus.$on('deleteQuickReply', (msg) => {
        if (msg.dataType === this.dataType) {
          let data = []
          this.dataObj.list.forEach((item) => {
            if (item.checked) {
              data.push(item._id)
            }
          })
          this.deleteQuickReply(data, true)
        }
      })
//      翻页
      bus.$on('getCount', (msg) => {
        if (msg.dataType === this.dataType) {
          this.searchCon = msg.content || ''
          this.refresh(msg.currentPage, msg.content)
        }
      })
    },
    beforeDestroy () {
      bus.$off('deleteQuickReply')
      bus.$off('getCount')
    },
    beforeMount () {
      this.refresh()
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .box_head
    background #F4F5F9
    height 40px
    line-height 40px
    overflow hidden
    span
      margin-left 2px
  .no_data
    text-align center
    line-height 30px
  .box_li
    height 40px
    line-height 40px
    border-bottom 1px solid #E7E7EB
    overflow hidden
    span
      margin-left 1px
      b
        font-weight unset
    .draggable_handle
      margin-left 20px
      cursor move
    .edit
    .del
      cursor pointer
    .edit
      color $c-main
    .del
      color $c-pink
      margin-left 20px
  .quickReplyLi
    max-height calc(100vh - 336px)
    overflow-y auto
  .new-config
    .quickReplyLi
      max-height calc(100vh - 182px)
  .km-right-wrap
    .quickReplyLi
      max-height calc(100vh - 160px)
  .user_pic_quick_reply
    .quickReplyLi
      max-height calc(100vh - 300px)
  .itemContent,.itemSortName
    span
      display inline-block
      width 100%
      white-space nowrap
      text-overflow ellipsis
      overflow hidden
  .check_box
    margin-left 10px
</style>
